<template>
	<view class="tabbarpage-container">
		<!--胶囊上方-->
		<view :style="{'padding-top': statusBarHeight}"></view>

		<!--胶囊-->
		<view class="page-header-back" :style="{ 'height': capsuleHeight }">
			<navigator open-type="navigateBack" hover-class="navigator-hover">
				<view class="back-icon">
					<wd-icon name="thin-arrow-left" size="18px"></wd-icon>
				</view>
			</navigator>
			<view class="title">
				生成练习
			</view>
			<view style="width: 18px">
				<!-- placeholder for symmetry -->
			</view>

		</view>

		<!--主体-->
		<view class="tabbarpage-body">
            <wd-config-provider theme="dark">
                <view class="gen-ex-page">
                    <CardCom title="选择时间段">
                        <wd-calendar type="daterange" v-model="value" @confirm="handleConfirm" />
                    </CardCom>
                    <CardCom title="选择你想练习的题目标签">
                        <!--标签-->
						<div class="ques-line" v-if="tags">
							<!-- <div>领域：</div> -->
							<div class="tags-container" v-if="tags.field">
								<div class="tag" v-for="(tag, index) in tags.field" :key="index">
									<div style="margin-right: 4px;">{{ tag }}</div>
									<wd-icon @click="deleteTag('field', index)" v-if="checkTag(tag)" name="close-bold" size="18px"></wd-icon>
								</div>
								<!--新增-->
								<div @click="addNewTag('field')" class="new-tag" v-if="tags.field.length < 4">
									<wd-icon name="add1" size="18px"></wd-icon>
								</div>
							</div>
							<!-- <div>题型：</div> -->
							<div class="tags-container" v-if="tags.category">
								<div class="tag" v-for="(tag, index) in tags.category" :key="index">
									<div style="margin-right: 4px;">{{tag}}</div>
									<wd-icon @click="deleteTag('category', index)" v-if="checkTag(tag)" name="close-bold" size="18px"></wd-icon>
								</div>
								<!--新增-->
								<div @click="addNewTag('category')" class="new-tag" v-if="tags.category.length < 4">
									<wd-icon name="add1" size="18px"></wd-icon>
								</div>
							</div>
							<!-- <div>错误原因：</div> -->
							<div class="tags-container" v-if="tags.falseReason">
								<div class="tag" v-for="(tag, index) in tags.falseReason" :key="index">
									<div style="margin-right: 4px;">{{tag.falseReason}}</div>
									<wd-icon @click="deleteTag('falseReason', index)" v-if="checkTag(tag)" name="close-bold" size="18px"></wd-icon>
								</div>
								<!--新增-->
								<div @click="addNewTag('falseReason')" class="new-tag" v-if="tags.falseReason.length < 4">
									<wd-icon name="add1" size="18px"></wd-icon>
								</div>
							</div>
						</div>
                    </CardCom>
                    <wd-button @click="submit" v-if="!submitted && !loading">提交</wd-button>
                    <wd-button type="success" @click="goToExerciseDetailPage" v-else-if="submitted && !loading">查看题目详情</wd-button>
					<wd-button loading v-if="loading">加载中</wd-button>
					<!-- <button @click="goToExerciseDetailPage" v-else-if="submitted">查看题目详情</button> -->
                    <NewTagCom @addTag=addTagSure @close=changeTagChangeShow v-if="showingAddTag"></NewTagCom>
                </view>
            </wd-config-provider>
		</view>

	</view>
</template>

<script>
import { globalProps } from '@/js/global.js'
import CardCom from '@/components/CardCom.vue'
import NewTagCom from '@/components/NewTagCom.vue'
import timestampToFormattedDateTime from '@/js/timestampToFormattedDateTime.js'
import quesTypeTranslator from '@/js/quesTypeTranslator.js'

export default {
	components: {
		CardCom,
		NewTagCom
	},
	data() {
		return {
			loading: false,
			exerciseList: [],
			statusBarHeight: globalProps.statusBarHeight,
			capsuleHeight: globalProps.capsuleHeight,
			value: Date.now(),
			tags: null,
			showingAddTag: false,
			submitted: false
		}
	},
	mounted() {
		// getTags()
		console.log(this.tags)
		uni.request({
			url: globalProps.baseApi + '/cuotiji/tagByTime',
			method: 'GET',
			data: {
				userID: globalProps.userInfo.id
			},
			success: (res) => {
				console.log('成功获取tag：', res.data)

				// 获取标签时翻译题目类型为中文
				res.data.category.forEach((tagCategory, index) => {
					res.data.category[index] = quesTypeTranslator(tagCategory);
				});
				this.tags = res.data
			},
			fail: (err) => {
				uni.showToast({
					title: '获取tag失败',
					icon: 'none'
				})
				console.log(err)
			}
		})
	},
	methods: {
		handleConfirm({ value }) {
			const startTime = timestampToFormattedDateTime(value[0])
			const endTime = timestampToFormattedDateTime(value[1])
			uni.request({
				url: globalProps.baseApi + '/cuotiji/tagByTime',
				method: 'GET',
				data: {
					startTime: startTime,
					endTime: endTime,
					userID: globalProps.userInfo.id
				},
				success: (res) => {
					console.log('成功获取tag：', res)

					// 获取标签时翻译题目类型为中文
					res.data.category.forEach((tagCategory, index) => {
						res.data.category[index] = quesTypeTranslator(tagCategory);
					});

					this.tags = res.data
				},
				fail: (err) => {
					uni.showToast({
						title: '获取tag失败',
						icon: 'none'
					})
					console.log(err)
				}
			})
		},
		redirect() {
			uni.navigateTo({
				url: '/pages/newques/SelectQuesPage/SelectQuesPage'
			})
		},
		checkTag(input) {
			const regex = /^(题型|.*题)$/i
			return !regex.test(input)
		},
		addNewTag(tagType) {
			this.changeTagChangeShow()
		},
		changeTagChangeShow() {
			this.showingAddTag = !this.showingAddTag
			console.log(this.showingAddTag)
		},
		addTagSure(e) {
			this.tags.push(e)
			this.changeTagChangeShow()
		},
		deleteTag(arrayName, tagIndex) {
			this.tags[arrayName].splice(tagIndex, 1)
		},
		submit() {
			this.loading = true
			console.log('提交前：', this.tags)

			// 使用map函数提取id数组
			const idArray = this.tags.falseReason.map(obj => obj.id)
			const categoryArray = this.tags.category.map(obj => obj)
			// 翻译回英文
			categoryArray.forEach((tagCategory, index) => {
				categoryArray[index] = quesTypeTranslator(tagCategory, "en");
			});
			const fieldArray = this.tags.field.map(obj => obj)
			console.log('发送data:', {
				category: categoryArray,
				falseReason: idArray,
				field: fieldArray,
				userID: globalProps.userInfo.id
			})
			let url = globalProps.baseApi + 'cuotiji/cuotiForRedo/?userID=' + globalProps.userInfo.id
			url += categoryArray.map(category => '&category=' + category).join('');
			url += idArray.map(id => '&falseReason=' + id).join('');
			url += fieldArray.map(field => '&field=' + field).join('');
			console.log(url);

			uni.request({
				// url: globalProps.baseApi + 'cuotiji/cuotiForRedo?' + category + field + '&userID=' + globalProps.userInfo.id,
				url: url,
				method: 'GET',
				//   data: {
				// 	category: categoryArray,
				// 	falseReason: idArray,
				// 	field: fieldArray,
				// 	userID: globalProps.userInfo.id
				//   },
				success: (res) => {
					console.log('成功生成练习：', res.data)
					this.exerciseList = res.data
					this.submitted = true
					uni.setStorageSync('exerciseList', res.data);
					this.loading = false
				},
				fail: (err) => {
					uni.showToast({
						title: '生成练习失败',
						icon: 'none'
					})
					console.log(err)
				}
			})
		},
		goToExerciseDetailPage() {
			// 假设this.exerciseList是获取的题目数组
			uni.navigateTo({
				url: '/pages/AIConsolidation/QuestionShowPage',
				// 将题目数组作为参数传递给ExerciseDetailPage页面
				success: (res) => {
					console.log('跳转成功', res);
					if (res.errMsg === 'navigateTo:ok') {
						// 传递参数
						// uni.setStorageSync('exerciseList', this.exerciseList);
					}
				}
			});
		}
	}
}
</script>

<style>
	@import "@/css/global.css";
	@import "@/css/animation.css";
	
	page{
		color:white;
	}

    .gen-ex-page{
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        height: 100%;
        margin: 10px 20px;
    }

    .ques-line{
		white-space: pre-line;
		word-break: break-all;
		display: flex;
		flex-direction: column;
	}
    .ques-line .tags-container{
		display: flex;
        flex-wrap: wrap;
        flex-wrap: wrap;
		align-items: center;
		justify-content: flex-start;
        /* margin-bottom: -10px; */
	}
	.tags-container .tag{
		background-color: #4942ad;
		padding: 4px 8px;
		font-size: 13px;
		margin-right: 8px;
		border-radius: 4px;
		margin-left: -2px;
        margin-bottom: 10px;
		display: flex;
		align-items: center;
		justify-content: space-around;
	}


</style>
